﻿using Autofac;
using Autofac.Extras.Quartz;
using Autofac.Integration.Mvc;
using JinfuyuanProject.Entity;
using JinfuyuanProject.Entity.Filter;
using JinfuyuanProject.Jobs;
using JinfuyuanProject.Repository;
using JinfuyuanProject.Service;
using JinfuyuanProject.Service.Service;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;


namespace JinfuyuanProject.App_Start
{
    public class AutofacConfig
    {
        public static void AutofacRegister()
        {

            // 创建一个容器对象
            var builder = new ContainerBuilder();

            // 依赖注入当前应用程序下的所有Controller
            builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();

            // 注册数据库上下文
            builder.RegisterType<JinfuyuanDbContext>().AsSelf().InstancePerLifetimeScope();
            builder.RegisterType<JinfuyuanMongoDbContext>().AsSelf().InstancePerLifetimeScope();
            builder.Register(c => new HttpContextWrapper(HttpContext.Current)).As<HttpContextBase>();

            // 注册过滤器
            builder.RegisterType<ParturientFilter>().AsSelf().InstancePerLifetimeScope();
            builder.RegisterType<ManagerFilter>().AsSelf().InstancePerLifetimeScope();
            builder.RegisterType<SalaryFilter>().AsSelf().InstancePerLifetimeScope();
            builder.Register(c => new HttpContextWrapper(HttpContext.Current)).As<HttpContextBase>().InstancePerRequest();
            //请求上下文类放入到了容器中：目的为了让服务层和其他各层能够拿到Session
            // 注册服务
            Assembly asmService = Assembly.Load("JinfuyuanProject.Service");

            builder.RegisterAssemblyTypes(asmService)
                   .Where(t => !t.IsAbstract)
                   .AsImplementedInterfaces()
                   .PropertiesAutowired();

            // 注册 LoginService
            builder.RegisterType<LoginService>().As<LoginService>().InstancePerLifetimeScope();

            // 注入所有非抽象成员的实体和仓储
            Assembly asmEntity = Assembly.Load("JinfuyuanProject.Entity");
            Assembly asmRepository = Assembly.Load("JinfuyuanProject.Repository");

            builder.RegisterAssemblyTypes(asmEntity)
                   .Where(t => !t.IsAbstract)
                   .AsImplementedInterfaces()
                   .PropertiesAutowired();

            builder.RegisterAssemblyTypes(asmRepository)
                   .Where(t => !t.IsAbstract)
                   .AsImplementedInterfaces()
                   .PropertiesAutowired();
            builder.RegisterModule(new QuartzAutofacFactoryModule()); // 提供ISchedulerFactory
            builder.RegisterModule(new QuartzAutofacJobsModule(typeof(TestJob).Assembly)); // 注册Job
            builder.RegisterModule(new QuartzAutofacJobsModule(typeof(DatabaseBackupJob).Assembly)); // 注册 Job
            builder.RegisterModule(new QuartzAutofacJobsModule(typeof(PaySalaryJob).Assembly)); // 注册 Job

            // 容器构建
            var container = builder.Build();
            // 配置Quartz任务
            var scheduler = container.Resolve<IScheduler>();
            ScheduleJobs(scheduler);
            scheduler.Start();
            // 替换依赖注入解析器
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));



        }
        private static void ScheduleJobs(IScheduler scheduler)
        {

            var job = JobBuilder.Create<TestJob>()
                .WithIdentity("homeStatusJob", "group1")
                .Build();

            var trigger = TriggerBuilder.Create()
                .WithIdentity("homeStatusTrigger", "group1")
                 .WithSchedule(CronScheduleBuilder.CronSchedule("0 0 10 * * ?")) // 每天10:01 AM//秒 分 时 日 月 星期 年（可选）                                   
                .Build();

            scheduler.ScheduleJob(job, trigger).Wait();
        }
        public void ScheduleDatabaseBackupJob(IScheduler scheduler)
        {
            // 创建数据库备份任务
            var job = JobBuilder.Create<DatabaseBackupJob>()
                                .WithIdentity("databaseBackupJob", "group1")
                                .Build();

            // 创建触发器，每7天执行一次
            var trigger = TriggerBuilder.Create()
                                        .WithIdentity("databaseBackupTrigger", "group1")
                                        .WithSchedule(CronScheduleBuilder.CronSchedule("0 0 0 */7 * ?")) // 每7天执行一次
                                        .Build();

            // 注册并调度任务
            scheduler.ScheduleJob(job, trigger).Wait();
            //scheduler.TriggerJob(job.Key).Wait();
        }
        public void SchedulePaySalaryJob(IScheduler scheduler)
        {
            // 创建薪资支付任务
            var job = JobBuilder.Create<PaySalaryJob>()
                                .WithIdentity("paySalaryJob", "group1")
                                .Build();
            // 创建触发器，每月1号执行
            var trigger = TriggerBuilder.Create()
                                        .WithIdentity("paySalaryTrigger", "group1")
                                        .WithSchedule(CronScheduleBuilder.CronSchedule("0 0 0 15 * ?")) // 每月15号执行
                                        .Build();
            // 注册并调度任务
            scheduler.ScheduleJob(job, trigger).Wait();
            // 立即执行一次任务
            //scheduler.TriggerJob(job.Key).Wait();
        }
    }
}